{
 "cells": [
  {
   "cell_type": "code",
   "id": "3ef49b02",
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "source": [
    "import pandas as pd\n",
    "from mlxtend.frequent_patterns import apriori, association_rules\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "\n",
    "# Step 1: Preprocess the dataset\n",
    "# Load the data\n",
    "# Note: Replace 'path_to_file.xlsx' with the actual path to the Excel file.\n",
    "df = pd.read_excel('Apriori_Data.xlsx')\n",
    "\n",
    "# Convert the dataset into a list of transactions\n",
    "transactions = df.groupby('Customer ID')['Movie ID'].apply(list).tolist()\n",
    "\n",
    "# Binarize the data for Apriori\n",
    "te = TransactionEncoder()\n",
    "te_ary = te.fit(transactions).transform(transactions)\n",
    "df = pd.DataFrame(te_ary, columns=te.columns_)\n",
    "\n",
    "# Step 2: Apply the Apriori algorithm\n",
    "# Find frequent itemsets with a minimum support threshold\n",
    "frequent_itemsets = apriori(df, min_support=0.1, use_colnames=True)  # Adjust the min_support if necessary\n",
    "\n",
    "# Step 3: Discover association rules\n",
    "rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.1)  # Adjust the min_threshold if necessary\n",
    "\n",
    "# Print the discovered frequent itemsets and association rules\n",
    "print(\"Frequent itemsets:\")\n",
    "print(frequent_itemsets.head())\n",
    "print(\"\\nTop 10 frequent itemsets with 2 items:\")\n",
    "count = 0  \n",
    "for index, row in frequent_itemsets.iterrows():\n",
    "    if len(row['itemsets']) == 2:  \n",
    "        print(f\"Itemset: {row['itemsets']}, Support: {row['support']:.4f}\")\n",
    "        count += 1\n",
    "        if count >= 10:  \n",
    "            break\n",
    "\n",
    "print(\"\\nAssociation rules:\")\n",
    "print(rules.head(10))\n",
    "\n",
    "# Step 4: Generate a sample recommendation\n",
    "# This function takes a list of movies (basket) and the discovered rules, and recommends a list of movies.\n",
    "def recommend_movies(basket, rules):\n",
    "    # Filter rules with antecedents in the basket\n",
    "    basket_rules = rules[rules['antecedents'].apply(lambda antecedents: antecedents.issubset(basket))]\n",
    "    # Sort rules by confidence\n",
    "    sorted_rules = basket_rules.sort_values(by='confidence', ascending=False)\n",
    "    # Get consequents of the top rule\n",
    "    recommendations = sorted_rules['consequents'].iloc[0] if not sorted_rules.empty else set()\n",
    "    # Return recommended movies not already in the basket\n",
    "    return list(recommendations - basket)\n",
    "\n",
    "# Assuming a customer's basket contains the following movies\n",
    "customer_basket = frozenset({32})\n",
    "# Generate recommendations\n",
    "recommended_movies = recommend_movies(customer_basket, rules)\n",
    "print(\"\\nRecommended movies based on the customer's basket:\")\n",
    "print('------')\n",
    "print(recommended_movies)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d1035ed",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
